package com.chenfan.process.common.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import lombok.extern.slf4j.Slf4j;

/**
 * @author K
 * @date 2021-05-10
 */
@Slf4j
public class ComputeEngine {

    private static final Pattern PATTERN = Pattern.compile("function\\s+([\\w_]+)(\\s+)?\\(");

    /**
     * 根据function获取结果
     *
     * @param param
     *            参数 这里的多参数要自定义
     * @param function
     *            方法
     * @return
     */
    public static String getResult(String param, String function) {

        String result = null;
        try {
            ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
            Matcher matcher = PATTERN.matcher(function);
            String method = null;
            if (matcher.find()) {
                method = matcher.group(1);
            }
            engine.eval(function);
            Invocable invocable = (Invocable)engine;
            result = invocable.invokeFunction(method, param).toString();

        } catch (Exception e) {
            log.error("js 引擎计算错误", e);
        }
        return result;
    }
}
